<template>
  <div>
    <el-dialog
      v-model="showDialog"
      width="797px"
      custom-class="form_dialog"
      append-to-body
      :close-on-click-modal="false"
      :before-close="closeDialog"
      v-dialog-drag
    >
      <template #header>
        <div class="manage_tit">
          <div class="line"></div>
          <p>场地看板编辑</p>
        </div>
      </template>
      <div class="form_item">
        <div class="relative" style="height: calc(100vh - 294px)">
          <el-tabs v-model="activeName" @tab-change="handleTypeClick">
            <el-tab-pane
              :name="item.type"
              v-for="(item, typeIndex) in siteTypeList"
              :key="item.type"
              :label="item.typeName"
            >
              <template #label>
                <div class="relative">
                  <span>{{ item.typeName }}</span>
                  <img
                    src="@/assets/images/icon/close_icon.png"
                    alt=""
                    class="del_type"
                    @click.stop="delType(item, typeIndex)"
                  />
                </div>
              </template>
              <div class="site_box">
                <div class="site_container">
                  <div v-for="(card, index) in item.siteList" :key="index" class="site_wrap">
                    <el-form
                      :ref="(el) => setFormRef(el, `${item.typeName}-${index}`)"
                      :model="item"
                      :rules="stadiumRules"
                      label-position="left"
                      label-width="84px"
                      class="stadium_form"
                    >
                      <div class="site_block" v-if="!card.isOpen">
                        <div class="flex items-center">
                          <p class="site_name">{{ card.siteName }}</p>
                          <div class="ml-4">
                            <el-switch
                              v-model="card.enable"
                              @change="(val) => changeEnable(val, card)"
                              active-value="1"
                              inactive-value="0"
                            >
                            </el-switch>
                            <span class="ml-2">{{ card.enable == '1' ? '启用' : '停用' }}</span>
                          </div>
                        </div>
                        <div class="flex items-center">
                          <div
                            class="edit_site"
                            @click="handleOpen(card)"
                            v-if="card.enable == '1'"
                          >
                            编辑
                          </div>
                          <div class="del_site" @click="delCard(card, index, item)">删除</div>
                        </div>
                      </div>
                      <div class="site_card" v-else>
                        <el-form-item
                          label="场地名称"
                          :prop="`siteList.${index}.siteName`"
                          :rules="stadiumRules.siteName"
                        >
                          <el-input clearable v-model="card.siteName" style="width: 155px">
                          </el-input>
                        </el-form-item>
                        <div class="flex items-center justify-between">
                          <el-form-item
                            label="场地长度"
                            :prop="`siteList.${index}.siteLong`"
                            :rules="stadiumRules.siteLong"
                          >
                            <el-input clearable v-model="card.siteLong" style="width: 90px">
                            </el-input>
                          </el-form-item>
                          <el-form-item
                            label="场地宽度"
                            :prop="`siteList.${index}.siteWide`"
                            :rules="stadiumRules.siteWide"
                          >
                            <el-input clearable v-model="card.siteWide" style="width: 90px">
                            </el-input>
                          </el-form-item>
                          <el-form-item
                            label="场地面积"
                            :prop="`siteList.${index}.siteArea`"
                            :rules="stadiumRules.siteArea"
                          >
                            <el-input clearable v-model="card.siteArea" style="width: 90px">
                            </el-input>
                          </el-form-item>
                        </div>
                        <div class="flex justify-between">
                          <div>
                            <el-form-item
                              label="场地标准"
                              :prop="`siteList.${index}.isStandard`"
                              :rules="stadiumRules.isStandard"
                              class="site_nature error_form"
                            >
                              <el-radio-group v-model="card.isStandard" style="width: 202px">
                                <el-radio :label="'0'">标准场</el-radio>
                                <el-radio :label="'1'">非标准场</el-radio>
                              </el-radio-group>
                            </el-form-item>
                            <el-form-item
                              label="用户性质"
                              :prop="`siteList.${index}.isIndependence`"
                              :rules="stadiumRules.isIndependence"
                              class="error_form"
                            >
                              <el-radio-group v-model="card.isIndependence">
                                <el-radio :label="'1'" style="width: 67px">散客</el-radio>
                                <el-radio :label="'0'">非散客</el-radio>
                              </el-radio-group>
                            </el-form-item>
                          </div>
                          <div>
                            <el-form-item
                              label="场地性质"
                              :prop="`siteList.${index}.siteNature`"
                              :rules="stadiumRules.siteNature"
                              class="site_nature error_form"
                            >
                              <el-radio-group v-model="card.siteNature">
                                <el-radio :label="'0'">全场</el-radio>
                                <el-radio :label="'1'">半场</el-radio>
                              </el-radio-group>
                            </el-form-item>
                            <el-form-item label="适用规格" class="site_specification">
                              <el-input
                                clearable
                                v-model="card.siteSpecification"
                                style="width: 155px"
                              >
                              </el-input>
                            </el-form-item>
                          </div>
                        </div>

                        <el-form-item
                          label="使用须知"
                          :prop="`siteList.${index}.orderInstructions`"
                          :rules="stadiumRules.orderInstructions"
                          v-if="card.isIndependence == '1'"
                        >
                          <el-input clearable v-model="card.orderInstructions" type="textarea">
                          </el-input>
                        </el-form-item>
                        <el-form-item
                          label="排序"
                          :prop="`siteList.${index}.siteSort`"
                          :rules="stadiumRules.siteSort"
                        >
                          <el-input clearable v-model="card.siteSort"> </el-input>
                        </el-form-item>

                        <div class="price_box">
                          <p class="price_tit">价格设置</p>
                          <div
                            v-for="(price, pIndex) in card.sitePriceEntities"
                            :key="pIndex"
                            class="price_item"
                          >
                            <el-form-item
                              label="价格"
                              :prop="`siteList.${index}.sitePriceEntities.${pIndex}.price`"
                              :rules="stadiumRules.price"
                            >
                              <el-input clearable v-model="price.price" style="width: 120px">
                              </el-input>
                            </el-form-item>
                            <el-form-item label="备注">
                              <el-input clearable v-model="price.remark" style="width: 155px">
                              </el-input>
                            </el-form-item>
                            <el-form-item label="默认价格">
                              <el-radio
                                v-model="price.defaultPrice"
                                @change="(val) => handleChangeDefault(val ?? false, price, card)"
                                label="1"
                                >是</el-radio
                              >
                              <el-radio v-model="price.defaultPrice" label="0">否</el-radio>
                            </el-form-item>
                            <div class="del_price" @click="delPrice(card, pIndex)">删除</div>
                          </div>
                          <div class="add_price" @click="addPrice(card)">+添加价格</div>
                        </div>
                        <div class="flex justify-end">
                          <el-button
                            type="primary"
                            size="small"
                            @click="saveSite(card, item.typeName + index)"
                            >保存</el-button
                          >
                          <el-button
                            size="small"
                            class="default_btn ml-4"
                            @click="delCard(card, index, item)"
                            >取消</el-button
                          >
                        </div>
                      </div>
                    </el-form>
                  </div>
                  <div
                    :class="['add_site', { have_site: item.siteList.length > 0 }]"
                    @click="handleAddSite(item)"
                  >
                    新增场地
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
          <div class="add_type" @click="addType">
            <img src="@/assets/images/icon/add.png" />
          </div>
        </div>
        <div class="form_btn submit_btn" v-if="siteTypeList.length > 0">
          <el-button type="primary" @click="handleSubmit">提交审核</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      v-model="showAddType"
      width="417px"
      append-to-body
      :close-on-click-modal="false"
      custom-class="dialog_center dialog_type"
      :modal="false"
    >
      <div>
        <p>新增场地类型</p>
        <el-form ref="addTypeFormRef" :rules="addTypeRules" :model="addTypeForm">
          <el-form-item prop="type">
            <el-select filterable clearable v-model="addTypeForm.type" placeholder="请选择">
              <el-option
                v-for="item in dictTypeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
                :disabled="item.disabled"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <div class="form_btn">
            <el-button type="primary" @click="handleAddType">确定</el-button>
            <el-button class="default_btn" @click="showAddType = false">取消</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <approval-dialog ref="approvalDialogRef" v-model="approvalVisible"></approval-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, defineProps, defineEmits, nextTick } from 'vue'
import uploadImg from '@/components/Upload/uploadImg.vue'
import approvalDialog from '../Approval/approvalDialog.vue'
import { debounce } from 'lodash'
import {
  saveSiteAndPrice,
  deleteSite,
  editSiteEnable,
  submitSiteApproval,
  delSiteByStadiumIdAndType,
} from '@/api/site/site'
import { listData } from '@/api/system/dict/data'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

// Props
interface SiteItem {
  id?: number
  siteName: string | null
  siteArea: string | null
  siteLong: string | null
  siteWide: string | null
  siteSpecification: string | null
  isStandard: string | undefined
  siteNature: string | undefined
  isIndependence: string
  orderInstructions: string
  siteSort: string | null
  sitePriceEntities: Array<{
    price: string
    remark: string
    defaultPrice: string
  }>
  isOpen: boolean
  enable?: string
}

interface SiteType {
  type: string
  typeName: string
  siteList: SiteItem[]
}

interface Props {
  show: boolean
  stadiumId: string | number | null
  stadiumType: string | number | null
  types: SiteType[]
}

const props = withDefaults(defineProps<Props>(), {
  show: false,
  stadiumId: null,
  stadiumType: null,
  types: () => [],
})

// Emits
const emit = defineEmits<{
  close: []
  addType: []
}>()

// Refs
const addTypeFormRef = ref<FormInstance>()
const approvalDialogRef = ref<InstanceType<typeof approvalDialog> | null>(null)

// Reactive data
const showDialog = ref(props.show)
const approvalVisible = ref(false)
const siteTypeList = ref<SiteType[]>([])
const showAddType = defineModel('showAddType', { default: false })
const dictTypeList = ref<any[]>([])
const areaTree = ref<any[]>([])
const dataStatus = defineModel('dataStatus', { default: '' })
const activeName = ref('')
const delSiteIds = ref<number[]>([]) // 删除的场地id
const delPriceIds = ref<number[]>([]) // 删除的价格id

const addTypeForm = reactive({
  type: null as string | null,
})

const addTypeRules = reactive<FormRules>({
  type: [
    {
      required: true,
      message: '请选择场地类型',
      trigger: 'change',
    },
  ],
})

const stadiumRules = reactive<FormRules>({
  siteName: [
    {
      required: true,
      message: '请输入场地名称',
      trigger: 'blur',
    },
  ],
  siteArea: [
    {
      required: true,
      message: '请输入场地面积',
      trigger: 'blur',
    },
  ],
  siteLong: [
    {
      required: true,
      message: '请输入场地长度',
      trigger: 'blur',
    },
  ],
  siteWide: [
    {
      required: true,
      message: '请输入场地宽度',
      trigger: 'blur',
    },
  ],
  isStandard: [
    {
      required: true,
      message: '请选择是否为标准场地',
      trigger: 'change',
    },
  ],
  siteNature: [
    {
      required: true,
      message: '请选择场地性质',
      trigger: 'change',
    },
  ],
  isIndependence: [
    {
      required: true,
      message: '请选择用户性质',
      trigger: 'change',
    },
  ],
  price: [
    {
      required: true,
      message: '请输入价格',
      trigger: 'blur',
    },
  ],
  orderInstructions: [
    {
      required: true,
      message: '请输入使用须知',
      trigger: 'blur',
    },
  ],
  siteSort: [
    {
      required: true,
      message: '请输入排序',
      trigger: 'blur',
    },
  ],
})

// Form refs
const formRefs = ref<Record<string, FormInstance | null>>({})

const setFormRef = (el: any, key: string) => {
  if (el) {
    formRefs.value[key] = el
  }
}

// Methods
// 获取场馆类型
const getDictTypeList = async () => {
  const params = {
    pageNum: 1,
    pageSize: 99,
    dictType: 'site_type',
  }
  try {
    const res = await listData(params)
    if (props.stadiumType == 0) {
      dictTypeList.value = res.rows
    } else {
      const typeName = res.rows.find((item: any) => item.dictValue == props.stadiumType).dictLabel
      dictTypeList.value = [{ dictLabel: typeName, dictValue: props.stadiumType as string }]
    }
  } catch (error) {
    console.error(error)
  }
}

// 新增场地类型弹窗 筛选没有选择过的类型
const addType = () => {
  showAddType.value = true
  dictTypeList.value.forEach((item1) => {
    const match = siteTypeList.value.find((item2) => item2.type == item1.dictValue)
    if (match) {
      item1.disabled = true
    }
  })
}

// 确认新增场地类型
const handleAddType = () => {
  addTypeFormRef.value?.validate(async (valid) => {
    if (valid) {
      if (dataStatus.value == 'add') {
        siteTypeList.value = []
      }
      const typeName = dictTypeList.value.find(
        (item) => item.dictValue == addTypeForm.type,
      ).dictLabel
      siteTypeList.value.push({
        type: addTypeForm.type as string,
        typeName,
        siteList: [],
      })
      activeName.value = addTypeForm.type as string
      addTypeForm.type = null
      nextTick(() => {
        addTypeFormRef.value?.clearValidate()
      })
      emit('addType')
      showAddType.value = false
      dataStatus.value = ''
    }
  })
}

// 删除场地类型
const delType = (item: SiteType, index: number) => {
  if (item.siteList.length == 0) {
    siteTypeList.value.splice(index, 1)
    activeName.value = siteTypeList.value[0]?.type || ''
  } else {
    ElMessageBox.confirm('是否确认删除该类型以及该类型下的所有场地')
      .then(() => {
        return delSiteByStadiumIdAndType({
          stadiumId: props.stadiumId,
          type: item.type,
        })
      })
      .then(() => {
        siteTypeList.value.splice(index, 1)
        activeName.value = siteTypeList.value[0]?.type || ''
        ElMessage.success('操作成功')
      })
      .catch(() => {})
  }
}

// 新增场地
const handleAddSite = (item: SiteType) => {
  const hasTrue = item.siteList.some((element) => element.isOpen === true)
  if (hasTrue) {
    ElMessage.error('请先保存场地信息')
    return
  }
  const newArr: SiteItem = {
    siteName: null,
    siteArea: null,
    siteLong: null,
    siteWide: null,
    siteSpecification: null,
    isStandard: undefined,
    siteNature: undefined,
    isIndependence: '0',
    orderInstructions: '',
    siteSort: null,
    sitePriceEntities: [
      {
        price: '',
        remark: '',
        defaultPrice: '1',
      },
    ],
    isOpen: true,
  }
  item.siteList.push(newArr)
}

// 切换类型
const handleTypeClick = () => {
  // Empty implementation as in original
}

// 场地展开收起
const handleOpen = (card: SiteItem) => {
  card.isOpen = true
}

// 取消编辑场地
const delCard = (card: SiteItem, index: number, row: SiteType) => {
  if (card.id) {
    delSiteIds.value.push(card.id)
    card.isOpen = false
  } else {
    row.siteList.splice(index, 1)
  }
}

// 新增 框中的添加价格
const addPrice = (card: SiteItem) => {
  card.sitePriceEntities.push({
    price: '',
    remark: '',
    defaultPrice: '0',
  })
}

// 删除价格
const delPrice = (card: SiteItem, index: number) => {
  // 如果只有一条价格，不能删除
  if (card.sitePriceEntities.length <= 1) {
    ElMessage.error('至少保留一条价格信息')
    return
  }
  const priceItem = card.sitePriceEntities[index]
  // 如果有id，记录到删除列表
  if ((priceItem as any).id) {
    delPriceIds.value.push((priceItem as any).id)
  }
  card.sitePriceEntities.splice(index, 1)
}

// 保存场地
const saveSite = async (card: SiteItem, formName: string) => {
  try {
    const formRef = formRefs.value[formName]
    if (!formRef) return

    await formRef.validate()

    const params = {
      ...card,
      stadiumId: props.stadiumId,
      type: activeName.value,
      delPriceIds: delPriceIds.value,
    }

    const res = await saveSiteAndPrice(params)
    if (res.code === 200) {
      ElMessage.success('保存成功')
      card.isOpen = false
      // Reset deletion lists
      delSiteIds.value = []
      delPriceIds.value = []
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 修改场地启用状态
const changeEnable = async (val: string | number | boolean, row: SiteItem) => {
  try {
    await editSiteEnable({
      id: row.id,
      enable: val,
    })
    ElMessage.success('操作成功')
  } catch (error) {
    // Revert the change if the API call fails
    row.enable = val === '1' ? '0' : '1'
  }
}

// 修改默认价格
const handleChangeDefault = (val: string | number | boolean, item: any, card: SiteItem) => {
  card.sitePriceEntities.forEach((ele) => {
    ele.defaultPrice = '0'
  })
  item.defaultPrice = '1'
}

// 提交审核
const handleSubmit = debounce(
  async () => {
    try {
      // Check if any site is open (unsaved)
      const hasSiteOpen = siteTypeList.value.some((type) =>
        type.siteList.some((site) => site.isOpen),
      )

      if (hasSiteOpen) {
        ElMessage.error('请先保存场地信息')
        return
      }

      if (props.stadiumId === null) {
        ElMessage.error('场馆ID不能为空')
        return
      }

      await submitSiteApproval(props.stadiumId)
      approvalVisible.value = true
      emit('close')
    } catch (e) {
      console.error(e)
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
) as () => void

// 关闭弹窗
const closeDialog = () => {
  emit('close')
}

// Watchers
watch(
  () => props.show,
  (val) => {
    showDialog.value = val
    if (val) {
      if (dataStatus.value == 'edit') {
        siteTypeList.value = props.types
        activeName.value = siteTypeList.value[0]?.type || ''
      }
      delSiteIds.value = []
      delPriceIds.value = []
    }
  },
)

// Lifecycle
onMounted(() => {
  // Any initialization code if needed
})

// Expose methods
defineExpose({
  getDictTypeList,
})
</script>

<style lang="scss" scoped>
:deep(.dialog_type) {
  border-radius: 11px;
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    padding: 15px 15px 10px !important;
  }
  p {
    font-size: 14px;
    color: #383838;
    margin-bottom: 26px;
  }
  .el-select {
    width: 100%;
  }
  .el-input__inner {
    height: 30px;
    line-height: 30px;
  }
  .el-form-item {
    margin-bottom: 27px;
  }
  .form_btn {
    display: flex;
    justify-content: flex-end !important;
    .el-button {
      width: 61px !important;
      height: 24px !important;
      line-height: 24px;
      border-radius: 6px;
      padding: 0;
    }
  }
}

:deep(.form_dialog) {
  border-radius: 11px;
  .el-dialog__body {
    padding: 0 19px 24px;
    .el-tabs__nav-wrap {
      padding-left: 11px;
      &::after {
        height: 1px;
      }
    }
    .el-tabs__header {
      margin-bottom: 10px;
    }
    .el-tabs__item {
      height: 30px;
      line-height: 30px;
      font-size: 16px;
      &.is-active {
        color: #0988fb;
      }
    }
    .del_type {
      position: absolute;
      right: -12px;
      top: 4px;
      width: 8px;
      height: 8px;
    }
    .add_type {
      position: absolute;
      top: 6px;
      right: 0;
    }
    .site_box {
      height: calc(100vh - 332px);
      overflow-y: auto;
      .site_container {
        .site_wrap {
          overflow: hidden;
          &:last-of-type {
            .site_card {
              margin-bottom: 10px;
            }
          }
          &:nth-child(2n) {
            .site_block {
              background: #e5e5e5;
            }
          }
        }
      }
      .site_block {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 50px;
        line-height: 50px;
        background: #f5f5f5;
        padding: 0 20px;
        .site_name {
          font-size: 14px;
          color: #383838;
        }
        .edit_site,
        .del_site {
          font-size: 14px;
          margin-left: 20px;
          cursor: pointer;
        }
        .edit_site {
          color: #0988fb;
        }
        .del_site {
          color: #ff4d4f;
        }
      }
      .site_card {
        padding: 16px 20px 20px;
        background: #fafafa;
        .site_nature {
          margin-bottom: 16px;
        }
        .site_specification {
          margin-bottom: 0;
        }
        .error_form {
          display: flex;
          align-items: center;
          .el-form-item {
            margin-bottom: 0;
            margin-right: 20px;
            &:last-child {
              margin-right: 0;
            }
          }
        }
        .price_box {
          margin: 20px 0;
          .price_tit {
            font-size: 14px;
            color: #383838;
            margin-bottom: 16px;
          }
          .price_item {
            display: flex;
            align-items: center;
            margin-bottom: 16px;
            &:last-child {
              margin-bottom: 0;
            }
            .el-form-item {
              margin-bottom: 0;
              margin-right: 20px;
              &:last-child {
                margin-right: 0;
              }
            }
            .del_price {
              font-size: 14px;
              color: #ff4d4f;
              margin-left: 20px;
              cursor: pointer;
            }
          }
          .add_price {
            font-size: 14px;
            color: #0988fb;
            cursor: pointer;
            margin-top: 16px;
          }
        }
      }
      .add_site {
        height: 50px;
        line-height: 50px;
        text-align: center;
        font-size: 14px;
        color: #0988fb;
        cursor: pointer;
        border: 1px dashed #0988fb;
        margin-top: 10px;
        &.have_site {
          margin-top: 0;
        }
      }
    }
  }
}
</style>
